import utils from '../../utils/util';
import WxValidate from '../../utils/WxValidate';
Component({
  /**
   * 组件的属性列表
   */
  properties: {},
  lifetimes: {
    attached: function () {

      this._provinceArr = [];
      this._cityArr = [];
      this._regionArr = [];

      this._provincesName = [];
      this._citysName = [];
      this._regionsName = [];

      this._currCityArr = [];
      this._currRegionArr = [];
      this.getAreaAddrData();
      this._compareShare = utils.getStorage('companyShare');
      this._compareShare.customUserInfo = JSON.parse(this._compareShare.customUserInfo) || [];
      // this._compareShare.customUserInfo.forEach(item => {
      //   if (item.title == '微信号') {
      //     item._name = 'wechatNo'
      //   } else if (item.title == '邮箱') {
      //     item._name = "email"
      //   }
      // });
      this.data.dynicCollectData = this._compareShare.isFillUserInfo * 1 ? this._compareShare.customUserInfo : [];
      this.data.isNeedAddress = (this._compareShare.enableAreaAgent == 1 || (this._compareShare.companyAuth && this._compareShare.companyAuth.enableNewAreaAgent == 1) || this._compareShare.enableXhAreaAgent == 1 || (this._compareShare.companyAuth && this._compareShare.companyAuth.enableShareholderAreaAgent == 1)) || (this._compareShare.isFillUserInfo == 1 && this._compareShare.enableWriteAddress == 1);
      this.setData({
        isNeedAddress: this.data.isNeedAddress,
        dynicCollectData: this.data.dynicCollectData
      });
      if (((this._compareShare.status == 2 && this._compareShare.registerBeforeShift == false) || this._compareShare.encodeCompanyId == 'ww67ok') && !this._compareShare.userMobile) {
        this._isRetrieve = true;
        this.showForm();
        console.log("xxxxxxxxxxxxxxxxx");
      } else {
        this._isRetrieve = false;
        console.log("yyyyyyyyyyyy")
      }
      this.getImgCode();
      this._initValidate();
    },
    detached: function () {}
  },

  /**
   * 组件的初始数据
   */
  data: {
    isShowForm: false, //显示表单
    isShowAccount: false,
    accountStep: 1,
    isShowPhoneAccount: false,
    dynicCollectData: [],
    addrPickerArray: [], //地址
    codeTime: 60,
    userList: [], //用户犁碑坳
    addrPickerIndex: [], //地址索引
    codeImgInfo: {}, //图形验证码
    isChooseAccount: false, //是否是账号平移
    chooseUserInfo: {}, //当前选中的用户
    otherUserList: [],
    currentUserInfo: null,
    otherParams: {}, //其他参数
    isNeedAddress: false, //是否需要填写用户地区
    mobileVal: "",
    imgCodeVal: "",
    codeVal: "",
    isTranslateAccount: false,
  },

  /**
   * 组件的方法列表
   */
  methods: {
    formSubmit(e) {
      console.log("e", e, this.data.formList);
      let params = e.detail.value;
      this._formData = params;
      if (!this._validateInstance.checkForm(params)) {
        const error = this._validateInstance.errorList[0];
        wx.showToast({
          title: error.msg,
          icon: "none",
        });
      } else {
        let idxs = this.data.addrPickerIndex;
        this._formSendData = {
          mobile: this._formData.mobile,
          code: this._formData.code,
        };
        this._formSendData.customUserInfo = this.data.dynicCollectData || [];
        if (this.data.isNeedAddress) {
          this._formSendData.address = {
            provinceId: this._provinceArr[idxs[0]].value,
            cityId: this._currCityArr[idxs[1]].value,
            areaId: this._currRegionArr[idxs[2]].value
          }
        }
        if (this.data.otherUserList.length) {
          // 绑定该手机的账号数大于1个，要走合并账号流程
          console.log("走账号合并流程")
          this.checkSendCode().then(res => {
            this.setData({
              isShowAccount: true
            })
          })
          return;
        }

        if (this.isRetrieve) {
          //账号平移
          console.log("走账号平移");
          this.retrieveAccount(sendData);
        } else {
          this.bindMobile()
        }
      }
    },
    retrieveAccount(data) {
      utils.post('members/newBindMobile', data).then(res => {
        utils.setStorage('companyShare', {
          userMobile: this._formData.mobile
        });
        this._compareShare.userMobile = this._formData.mobile;
        this.bindGetIntegration();
        if (res.account) {
          let currentUserInfo = null,
            chooseUserInfo = {},
            otherUserList = [];
          if (Array.isArray(res.account)) {
            res.account.forEach((item, index) => {
              if (item.userId == this._compareShare.userId) {
                currentUserInfo = item;
              } else {
                otherUserList.push(item);
              }
            })
            if (!currentUserInfo) {
              chooseUserInfo = otherUserList[0];
            }
          }
          this.setData({
            isShowAccount: true,
            isTranslateAccount: true,
            currentUserInfo: currentUserInfo,
            otherUserList: otherUserList,
            chooseUserInfo: chooseUserInfo
          })

        } else {
          wx.showToast({
            title: '绑定成功',
          });
          this.triggerEvent("submitSuccess", this.data.otherParams)
        }
      })
    },
    openConfirmTip() {
      wx.showModal({
        title: '提示',
        content: `确定要将${this.data.otherUserList[0].nickname}的数据迁移到${this.data.currentUserInfo.nickname}吗?`,
        success: (res) => {
          if (res.confirm) {
            if (this.data.isTranslateAccount) {
              this.confirmMerge();
            } else if (this.data.otherUserList.length) {
              console.log("accountMerge")
              this.accountMerge();
            } else {
              this.bindMobile();
            }
          }
        }
      })
    },
    //账号合并
    accountMerge(data = this._formSendData) {
      console.log("accountMerge", data)
      utils.post('members/bindMobile', data).then(() => {
        let sendData = {
          mobile: data.mobile,
          verifyCode: data.code,
          fromApp: 'qt',
          companyId: this._compareShare.encodeCompanyId,
          userId: this.data.chooseUserInfo.userId,
          cancelUserId: []
        }
        this.data.otherUserList.forEach(item => {
          sendData.cancelUserId.push(item.userId);
        });
        utils.post('accountConnect/accountCombine', sendData).then(res => {
          if (res.t != "" && res.u != "" && res.c != null) {
            wx.showToast({
              title: '合并成功'
            });
            this.setData({
              isShowForm: false,
              isShowAccount: false
            })
            utils.setStorage("companyShare", {
              userMobile: this._formSendData.mobile
            })
            this._compareShare.userMobile = this._formData.mobile;
            this.triggerEvent("submitSuccess", this.data.otherParams)
          }
        })
      })

    },
    confirmMerge() {
      let sendData = {
        mobile: this.data.chooseUserInfo.mobile,
        selectedUserId: this.data.chooseUserInfo.userId,
        code: this._formData.code,
        companyId: this._compareShare.encodeCompanyId
      }
      utils.post('members/confirmBindMobile', sendData).then(res => {
        wx.showToast({
          title: '找回成功',
        });
        this.setData({
          isShowForm: false,
          isShowAccount: false
        })
        this.triggerEvent("submitSuccess", this.data.otherParams)
      })
    },
    onAccountClose() {
      this.setData({
        accountStep: 1
      })
    },
    //
    dynicCollectInput(e) {
      let index = e.currentTarget.dataset.index;
      let val = e.detail.value;
      this.data.dynicCollectData[index].content = val;
      this.setData({
        dynicCollectData: this.data.dynicCollectData
      })
    },
    //选中当前
    chooseUserInfo(e) {
      if (this.data.accountStep != 1) return;
      let data = e.currentTarget.dataset.item;
      console.log("e", e);
      this.setData({
        chooseUserInfo: data
      })
    },
    goNextStep() {
      this.data.accountStep = this.data.accountStep + 1;
      let chooseUserInfo = this.data.chooseUserInfo;
      let currentUserInfo = this.data.currentUserInfo;
      let newCurrentUserInfo = currentUserInfo;
      if (chooseUserInfo.userId == currentUserInfo.userId) {
        this.data.otherUserList.forEach(item => {
          newCurrentUserInfo.balance = (Number(newCurrentUserInfo.balance) + Number(item.balance)).toFixed(2);
          newCurrentUserInfo.couponNum = (Number(newCurrentUserInfo.couponNum) + Number(item.couponNum)).toFixed(2);
          newCurrentUserInfo.courseNum = (Number(newCurrentUserInfo.courseNum) + Number(item.courseNum)).toFixed(2);
          newCurrentUserInfo.points = (Number(newCurrentUserInfo.points) + Number(item.points)).toFixed(2);
          newCurrentUserInfo.coinAmount = (Number(newCurrentUserInfo.coinAmount) + Number(item.coinAmount)).toFixed(2);
          item.balance = 0;
          item.couponNum = 0;
          item.courseNum = 0;
          item.points = 0;
          item.coinAmount = 0;
          item.vipType = 0;
          item.vipName = '';
        })
      } else {
        //选中了其他的账户
        let index = this.data.otherUserList.findIndex(item => item.userId == chooseUserInfo.userId);
        if (index != -1) {
          newCurrentUserInfo = this.data.otherUserList.splice(index, 1)[0];
          this.data.otherUserList.push(currentUserInfo);
          this.data.otherUserList.forEach(item => {
            newCurrentUserInfo.balance = (Number(newCurrentUserInfo.balance) + Number(item.balance)).toFixed(2);
            newCurrentUserInfo.couponNum = (Number(newCurrentUserInfo.couponNum) + Number(item.couponNum)).toFixed(2);
            newCurrentUserInfo.courseNum = (Number(newCurrentUserInfo.courseNum) + Number(item.courseNum)).toFixed(2);
            newCurrentUserInfo.points = (Number(newCurrentUserInfo.points) + Number(item.points)).toFixed(2);
            newCurrentUserInfo.coinAmount = (Number(newCurrentUserInfo.coinAmount) + Number(item.coinAmount)).toFixed(2);
            item.balance = 0;
            item.couponNum = 0;
            item.courseNum = 0;
            item.points = 0;
            item.coinAmount = 0;
            item.vipType = 0;
            item.vipName = '';
            item.fromChannel = [];
          })
        }
      }
      this.setData({
        currentUserInfo: newCurrentUserInfo,
        otherUserList: this.data.otherUserList,
        accountStep: this.data.accountStep
      })
      console.log("currentUserInfo", newCurrentUserInfo, "otherUserList", this.data.otherUserList)
    },
    bindMobile(data = this._formSendData) {
      console.log("data", data);
      this.bindGetIntegration();
      return utils.post('members/bindMobile', data).then(() => {
        wx.showToast({
          title: '绑定成功'
        });
        this.setData({
          isShowForm: false,
          isShowAccount: false
        })
        utils.setStorage("companyShare", {
          userMobile: this._formSendData.mobile
        })
        this._compareShare.userMobile = this._formData.mobile;
        this.triggerEvent("submitSuccess", this.data.otherParams)
      })
    },
    bindGetIntegration() {
      if (this._compareShare.companyAuth.enableBindPhonePoint != 1) return;
      utils.post('common/getPoints', {
        cId: -1,
        extId: -1,
        pointFrom: 55,
        duration: -1
      }).then(res => {})
    },
    checkSendCode() {
      return utils.post('accountConnect/checkSendCode', {
        'mobile': this._formData.mobile,
        'verifyCode': this._formData.code,
        'fromApp': 'qt',
        'companyId': this._compareShare.encodeCompanyId
      })
    },
    hideAccount() {
      this.setData({
        isShowAccount: false
      });
    },
    showForm(data) {
      this.setData({
        mobileVal: "",
        imgCodeVal: "",
        codeVal: "",
        isTranslateAccount: false,
        isShowForm: true
      })
      this.setData({
        otherParams: data || {}
      })
    },
    hideForm() {
      this.setData({
        isShowForm: false
      })
    },
    //获取图像验证码
    getImgCode() {
      utils.get('common/captcha').then(res => {
        this.setData({
          codeImgInfo: res
        })
      })
    },
    //
    imgCodeInput(e) {
      this._imgCodeVal = e.detail.value;
      console.log(this._imgCodeVal);
    },
    addrPickerConfirm(e) {
      console.log('picker发送选择改变，携带值为', e.detail.value);
      this.setData({
        isAddrHadChange: true,
        addrPickerIndex: e.detail.value
      });
    },
    addrPickerColumnChange() {
      this._addrPickerIndexOld = [...this.data.addrPickerIndex];
      console.log('修改的列为', e.detail.column, '，值为', e.detail.value, this._addrPickerIndexOld);
    },
    addrPickerCancel() {
      console.log("bindAddrPickerCancel");
      let currCityChild = this._getCurrAddrChild(this._cityArr, this._provinceArr[this._addrPickerIndexOld[0]].value);
      let currRegionChild = this._getCurrAddrChild(this._regionArr, currCityChild.lists[0].value);
      this.data.addrPickerArray[1] = currCityChild.names;
      this.data.addrPickerArray[2] = currRegionChild.names;
      this._currCityArr = currCityChild.lists;
      this._currRegion = currRegionChild.lists;
      this.setData({
        addrPickerArray: this.data.addrPickerArray,
        addrPickerIndex: this._addrPickerIndexOld
      })
    },
    addrPickerColumnChange(e) {
      this._addrPickerIndexOld = [...this.data.addrPickerIndex];
      console.log('修改的列为', e.detail.column, '，值为', e.detail.value, this._addrPickerIndexOld);
      let data = {
        addrPickerArray: this.data.addrPickerArray,
        addrPickerIndex: this.data.addrPickerIndex
      }
      let currCityChild = {},
        currRegionChild = {};
      data.addrPickerIndex[e.detail.column] = e.detail.value;
      switch (e.detail.column) {
        case 0:
          currCityChild = this._getCurrAddrChild(this._cityArr, this._provinceArr[e.detail.value].value);
          currRegionChild = this._getCurrAddrChild(this._regionArr, currCityChild.lists[0].value);
          this._currCityArr = currCityChild.lists;
          this._currRegionArr = currRegionChild.lists;
          data.addrPickerArray[1] = currCityChild.names;
          data.addrPickerArray[2] = currRegionChild.names;
          data.addrPickerIndex[1] = 0;
          data.addrPickerIndex[2] = 0;
          break;
        case 1:
          currRegionChild = this._getCurrAddrChild(this._regionArr, this._currCityArr[e.detail.value].value);
          this._currRegionArr = currRegionChild.lists;
          data.addrPickerArray[2] = currRegionChild.names;
          data.addrPickerIndex[2] = 0;
          break;
      }
      this.setData(data)
    },
    _getCurrAddrChild(list, pid) {
      let res = {
        lists: [],
        names: [],
      };
      list.forEach(item => {
        if (item.parent == pid) {
          res.lists.push(item);
          res.names.push(item.name);
        }
      });
      // console.log("_getCurrAddrChild", res);
      return res;
    },
    //获取地址数据
    getAreaAddrData() {
      utils.get('common/getAreaListForAgent').then(res => {
        this.setData({
          areaAddrData: res.data
        });
        res.data.forEach(item => {
          if (item.level == 1) {
            this._provinceArr.push(item);
            this._provincesName.push(item.name);
          } else if (item.level == 2) {
            this._cityArr.push(item);
            this._citysName.push(item.name);
          } else if (item.level == 3) {
            this._regionArr.push(item);
            this._regionsName.push(item.name)
          }
        });
        let cityChild = this._getCurrAddrChild(this._cityArr, this._provinceArr[0].value);
        let regionChid = this._getCurrAddrChild(this._regionArr, cityChild.lists[0].value);
        this._currCityArr = cityChild.lists;
        this._currRegionArr = regionChid.lists;
        this.setData({
          addrPickerArray: [this._provincesName, cityChild.names, regionChid.names]
        });
        this._addrPickerIndexOld = this.data.addrPickerIndex; //初始化前一次选择的值
        // console.log("address", this._provinceArr, this._provincesName, this._cityArr, this._citysName, this._regionArr, this._regionsName)
      })
    },
    //获取手机验证码
    getPhoneCode() {
      if (!/^1[3456789]\d{4,9}$/.test(this._mobileVal)) {
        wx.showToast({
          title: '请输入正确的手机格式',
          icon: 'none'
        });
        return;
      } else if (!this._imgCodeVal || !/^\d{4}$/.test(this._imgCodeVal)) {
        wx.showToast({
          title: '请输入正确图形验证码',
          icon: 'none'
        });
        return;
      }
      if (this._phoneNumerTimer !== null) {
        clearTimeout(this._phoneNumerTimer);
      }
      this._phoneNumerTimer = setTimeout(() => {
        utils.post('members/sendCode', {
          mobile: this._mobileVal,
          isBindMobile: !this._isRetrieve,
          captcha: this._imgCodeVal,
          captchaKey: this.data.codeImgInfo.key,
        }).then(() => {
          wx.showToast({
            title: '验证码将在10分钟内有效！',
            icon: "none"
          })
          this._phoneCodeCountdown();
        })
      })
    },
    mobileInput(e) {
      console.log("e", e);
      this._mobileVal = e.detail.value;
    },
    mobileBlur(e) {
      console.log("e", e);
      this._mobileVal = e.detail.value;
      if (!this._mobileVal || !/^1[3456789]\d{4,9}$/.test(this._mobileVal)) return;
      utils.get('common/getCustomerUserInfo', {
        companyId: this._compareShare.encodeCompanyId,
        mobile: this._mobileVal
      }).then(res => {
        console.log([...res.currentUserInfo, ...res.userInfo])
        this.setData({
          chooseUserInfo: res.currentUserInfo.length ? res.currentUserInfo[0] : {},
          otherUserList: res.userInfo || [],
          currentUserInfo: res.currentUserInfo[0] || null,
        });
      })
    },
    //获取验证码倒计时
    _phoneCodeCountdown: function () {
      this._codeTimer = setInterval(() => {
        this.setData({
          codeTime: this.data.codeTime - 1
        });
        if (this.data.codeTime < 1) {
          clearInterval(this._codeTimer);
          this.setData({
            codeTime: 60
          });
        };
      }, 1000)
    },
    _initValidate() {
      let rules = {
        mobile: {
          required: true,
          digits: true
        },
        imgCode: {
          required: true,
        },
        code: {
          required: true,
          digits: true
        }
      };
      let messages = {
        mobile: {
          required: "请输入手机号",
          digits: "手机号必须是数字"
        },
        imgCode: {
          required: "请输入图形验证码"
        },
        code: {
          required: "请输入短信验证码",
          digits: "短信验证码必须是数字"
        }
      };
      if (this.data.isNeedAddress) {
        rules['address'] = {
          required: true
        }
        messages['address'] = {
          required: "请输入地址"
        }
      }
      console.log("this.data.dynicCollectData", this.data.dynicCollectData)
      this.data.dynicCollectData.forEach((item, index) => {
        if (item.require) {
          rules[`${index}`] = {
            required: true
          };
          messages[`${index}`] = {
            required: `请输入${item.title}`
          }
        }
      });
      console.log("rules", rules)
      this._validateInstance = new WxValidate(rules, messages);
    },
  }
})